$(function (){
	//加载树
	loadRightTree();
	//初始化jqGrid
	initGrid();
	
	$("#delBut").click(function(){
		var rowdata=ifOneAndData("user-table");
		if(rowdata){
			$('#removeDiv').dialog({
			resizable: false,
			modal: true,
			width: 300,
			title: "警告",
			title_html: true,
			buttons: [
				{
					html: "<i class='icon-trash bigger-110'></i>&nbsp; Delete ",
					"class" : "btn btn-xs btn-danger",
					click: function() {$( this ).dialog( "close" );}
				}
				,
				{
					html: "<i class='icon-remove bigger-110'></i>&nbsp; Cancel",
					"class" : "btn btn-xs",
					click: function() {$( this ).dialog( "close" );}
				}
			]
			});
			$('#removeDiv').dialog('open');
		}
			
	})
})

function initGrid(){
	 $("#menu-table").jqGrid({
		 url : '',
		 datatype : "json",
    colNames : [
                 "编码",
                 "名称",
                 "是否可用",
                 "排序号"
               ],
    colModel : [ 
                 {
                      name  : 'CODE',  //绑定的值
                      index : 'CODE',   //排序的值
                      width:200
                  },
                  {
                	  name  : 'NAME',
                	  index : 'NAME',
                	  width:200
                  },
                  { 
                	  name    : 'DISABLE_FLAGE',
                	  index   : 'DISABLE_FLAGE',
                	  width:200
                  },
                  { 
                	  name    : 'SORT_NUMBER',
                	  index   : 'SORT_NUMBER',
                	  width:200
                  }
				],
				rownumbers : true,//显示行号
				rowNum : 10, //设置表格显示的记录数 
				rowList : [10, 30, 50],//  可选择每页显示的条数
				pager : '#menu-pager',// 分页栏ID  必须是div
				viewrecords : true,// 定义是否要显示总记录数
				autowidth : true,
				multiselect: true,
				sortorder : "desc", //默认排序（asc or desc）
			    multiboxonly: true,
			    altRows: true,
				jsonReader : {
					root : 'list',// 结果集
					total : 'totalPage', // 总页数
					page : 'pageNumber', // 页码
					records : 'totalRow', // 总记录数
					repeatitems : false
				},
				loadComplete : function() {
					var table = this;
					setTimeout(function(){
						updatePagerIcons(table);
//						enableTooltips(table);
					}, 0);
				},
				height : 300
			});
	 

	 $("#menu-table").jqGrid('navGrid', '#page', {edit : false,add : false,del : false,search : false});
		function updatePagerIcons(table) {
			var replacement = 
			{
				'ui-icon-seek-first' : 'icon-double-angle-left bigger-140',
				'ui-icon-seek-prev' : 'icon-angle-left bigger-140',
				'ui-icon-seek-next' : 'icon-angle-right bigger-140',
				'ui-icon-seek-end' : 'icon-double-angle-right bigger-140'
			};
			$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
			})
		}	

		$("#addBut").click(function (){ 
			userDialog("add");
		})
		//修改
		$("#updateBut").click(function(){
			var rowdata=ifOneAndData("menu-table");
			if(rowdata){
				showUpdate(rowdata.CODE);
			}
		})

}

function loadRightTree(){
	var setting = {	
			async: {
				enable: true,
				contentType: "application/json",
				url:templateRoot+"menu/getTree",
				autoParam:["id", "name"]
				//dataFilter: filter 	预处理
			},
			data: {
				key: {
					children: "nodes"
				}
			},
			callback: {
				onClick: checkTree,
				onAsyncSuccess:initSelectTree
			}
	};
		$.fn.zTree.init($("#treeDemo"), setting);
}

//树节点单击
var selectTreeId;
function checkTree(event,treeId, treeNode,clickFlag){
	if(!treeNode.isParent){
		return;
	}
	var param={
		"PARENT_ID":treeNode.id
	}
	selectTreeId=treeNode.id;
	queryByParam(param);
}

function  queryByParam(param) {  
    var postData = $("#menu-table").jqGrid("getGridParam", "postData");   
    //将查询参数融入postData选项对象
    $.extend(postData, param);   
    $("#menu-table").jqGrid("setGridParam", { 
        url:templateRoot+"menu/findMenu"
    }).trigger("reloadGrid", [{page:1}]);   // (7)重新载入Grid表格，以使上述设置生效 
}

///下拉Tree
function initSelectTree(event,treeId,treeNode){
	var setting = {
			view: {
				dblClickExpand: false
			},
			data: {
				simpleData: {
					enable: true
				},
				key: {
					children: "nodes"
				}
			},
			callback: {
				beforeClick: beforeClick,
				onClick: onClick
			}
		};
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	var nodes=zTree.getNodes();
	$.fn.zTree.init($("#selectTree"), setting,nodes);
}

function beforeClick(treeId, treeNode) {
	var check = (treeNode && !treeNode.isParent);
	return check;
}

function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("selectTree");
	nodes = zTree.getSelectedNodes();
	layer.alert(nodes[0].id);
	$("#PARENT_ID").val(nodes[0].id);
	v = "";
	nodes.sort(function compare(a,b){return a.id-b.id;});
	for (var i=0, l=nodes.length; i<l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0 ) v = v.substring(0, v.length-1);
	var cityObj = $("#seLectMenu");
	cityObj.attr("value", v);
}

function showMenu() {
	var cityObj = $("#seLectMenu");
	var cityOffset = $("#seLectMenu").offset();
	//css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px" ,"z-index":"1"})
	$("#menuContent").css({left:"270px","z-index":"1"}).slideDown("fast");
	$("body").bind("mousedown", onBodyDown);
}
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
		hideMenu();
	}
}
function userDialog(opType){
	$('#addDiv').dialog({
	    autoOpen: false,
	    width: 800,
	    title:"新增",
		buttons: [
					{
						html: "<i class='icon-ok bigger-110'></i>&nbsp;保存",
						"class" : "btn btn-xs btn-success",
						click: function() {
							if($("#usableFlag").val()=="no"){
								$("#usableFlag").val("0");
							}else{
								$("#usableFlag").val("1");
							}
							saveOrUpdate(opType);
						}
					}
					,
					{
						html: "<i class='icon-remove bigger-110'></i>&nbsp; 取消",
						"class" : "btn btn-xs",
						click: function() {
							$( this ).dialog( "close" );
						}
					}
				]
	});
	$('#addDiv').dialog('open');
}
function showUpdate(CODE){
	$.ajax({
		type : 'POST',
		data : {
			CODE : CODE
		},
		url : '/menu/getMenu',
		datatype : "json",
		success : function(data) {
			if (data) {
				$("#addOrUpdateForm").loadValues(data.data);
				userDialog("update");
			} else {
				
			}
		},
		error : function(data) {
		}
	});
}
/**
 * 保存 
 * @param opType 操作类型
 */
function saveOrUpdate(opType){
	if(!selectTreeId){
		layer.alert("no");
		return;
	}
	var url=opType=="add"?"/menu/save":"/menu/update";
	var params = $("#addOrUpdateForm").serializeObject();
	layer.alert($("#PARENT_ID").val());
//	params["menu.PARENT_ID"]=selectTreeId;
	$.ajax({
		type : 'POST',
		data :params,
		url : url,
		datatype : "json",
		success : function(data) {
			if (data.success==true) {
				$('#addDiv').dialog('close');
				layer.msg("Success");
				loadParam();
			} else {
			}
		},
		error : function(data) {
			$('#addDiv').dialog('close');
		}
	});
}


//判断jqGrid只能选择一条进行编辑，并返回该条数据
function ifOneAndData(jqGridID){
    var rowData = null;
    var selectedRowIds = $("#" + jqGridID).jqGrid('getGridParam', 'selarrrow');
    if (selectedRowIds.length == 0) {
    	alert("请选择一条记录!");
        return null;
    }
    else 
        if (selectedRowIds.length > 1) {
            alert("每次只能对一条记录进行编辑!");
            return null;
        }
        else {
            rowData = $("#" + jqGridID).jqGrid("getRowData", selectedRowIds[0]);
        }
    return rowData;
}

function loadParam(params){
	var layerId = layer.load();
    var postData = $("#user-table").jqGrid("getGridParam", "postData");   
    //将查询参数融入postData选项对象
    $.extend(postData, params);   
    $("#user-table").jqGrid("setGridParam", { 
        search: true
    }).trigger("reloadGrid", [{page:1}]);   // (7)重新载入Grid表格，以使上述设置生效 
    
    //刷新树
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    treeObj.reAsyncChildNodes(null, "refresh");
    layer.close(layerId);
}

			